package com.raos.example.redisexample.controller;

import com.alibaba.fastjson.JSON;
import com.raos.example.redisexample.constants.BloomFilterCache;
import com.raos.example.redisexample.constants.RedisKeyConstants;
import com.raos.example.redisexample.dal.model.City;
import com.raos.example.redisexample.service.ICityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * 城市 前端控制器
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/7/22 22:01
 */
@RestController
@RequestMapping("/city")
public class CityController {

    @Autowired
    ICityService cityService;

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/{id}")
    public ResponseEntity<City> city(@PathVariable("id") Integer id) {
        System.out.println("普通的数据库访问");
        City city = cityService.getById(id);
        return ResponseEntity.ok(city);
    }

    @GetMapping("/redis/{id}")
    public ResponseEntity<City> cityRedis(@PathVariable("id") Integer id) {
        System.out.println("普通的redis访问");
        String city = (String) redisTemplate.opsForValue().get(RedisKeyConstants.CITY_KEY + ":" + id);
        return ResponseEntity.ok(JSON.parseObject(city, City.class));
    }

    @GetMapping("/bloom/{id}")
    public String filter(@PathVariable("id") Integer id) {
        System.out.println("升级的redis访问--基于布隆过滤器");
        String key = RedisKeyConstants.CITY_KEY + ":" + id;
        // 布隆过滤器 解决缓存穿透
        if (BloomFilterCache.cityBloom.mightContain(key)) {
            return redisTemplate.opsForValue().get(key).toString();
        }
        return "数据不存在";
    }

}
